package com.dev.ac.handler;


import com.dev.ac.common.Result;
import com.dev.ac.exception.WebException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.NoHandlerFoundException;

/**
 * @Author 付
 * @Date 2024-03-14 17:59
 * @Version 1.0
 * @description
 * @since 1.0
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
	@ExceptionHandler(value = WebException.class)
	@ResponseStatus(HttpStatus.BAD_REQUEST)
	public Result handler(WebException webException){
		log.error("出现自定义异常(状态异常)------->"+webException.getMessage());
		return Result.error(webException.getMessage());
	}
	@ExceptionHandler(value = Exception.class)
	@ResponseStatus(HttpStatus.BAD_REQUEST)
	public Result handler(Exception e){
		log.error("出现自定义异常(全局异常)------->"+e.getMessage());
		e.printStackTrace();
		return Result.error(e.getMessage());
	}

	@ExceptionHandler(value = NoHandlerFoundException.class)
	@ResponseStatus(HttpStatus.NOT_FOUND)
	public Result handler(NoHandlerFoundException e){
		log.error("出现自定义异常(未创建异常)------->"+e.getMessage());
		e.printStackTrace();
		return Result.error("404！页面不存在",404);
	}

	@ExceptionHandler(value = BindException.class)
	@ResponseStatus(HttpStatus.NOT_FOUND)
	public Result handler(BindException e){
		BindingResult bindingResult = e.getBindingResult();
		ObjectError objectError = bindingResult.getAllErrors().stream().findFirst().get();
		log.error("出现自定义异常(绑定异常)------->"+objectError.getDefaultMessage());
		e.printStackTrace();
		return Result.error("属性验证异常------->"+objectError.getDefaultMessage(),404);
	}
}
